#ifndef COMBINEJOINT_H
#define COMBINEJOINT_H

#include <map>
#include <string>
#include <mutex>
#include "../CXScheduler.h"
#include "../io/SerializeBasic.h"

namespace fs = std::filesystem;
typedef unsigned long  StepID;

struct RobotData {
    std::string robotType;
    std::string station;
    StepID startTime;
    StepID endTime;
    int duration;
    std::string partName; // 替换原来的 工件名称
    int wrlID;
    int partID;
    JointJsonPack axisData; // 替换原来的 轴数据
};

static std::vector<RobotData> readCSV(const std::string& filePath) {
    std::vector<RobotData> data;
    std::ifstream file(filePath);
    if (!file.is_open()) {
        std::cerr << "Failed to open file: " << filePath << '\n';
        return data;
    }

    std::string line;
    std::getline(file, line);

    while (std::getline(file, line)) {
        std::stringstream ss(line);
        std::string cell;
        RobotData record;

        std::getline(ss, record.robotType, ',');
        std::getline(ss, record.station, ',');
        std::getline(ss, cell, ',');
        record.startTime = std::stoi(cell);
        std::getline(ss, cell, ',');
        record.endTime = std::stoi(cell);
        std::getline(ss, cell, ',');
        record.duration = std::stoi(cell);
        std::getline(ss, record.partName, ',');
        std::getline(ss, cell, ',');
        record.wrlID = std::stoi(cell);
        std::getline(ss, cell, ',');
        record.partID = std::stoi(cell);
        std::string xxx;
        std::getline(ss, xxx, ',');

        record.axisData = GetJsonByPath(xxx);
        data.push_back(record);
    }

    return data;
}

typedef std::vector<MJointData> CXJ;


struct CSVRowJoint{
    StepID startStep{0};
    StepID endStep{0};

    int duraing{0};
    int station{1};

    TaskType typ;

    void ReadJointByJson(JointJsonPack js);

    CXJ joints;
    int real_chain;

    int wrlID;
    int partID;
};


class KeyMutexMap {
public:
    std::mutex& getMutexForKey(const StepID& key) {
        // 如果没有找到对应的互斥锁，则插入一个新的
        return _mutexes[key];
    }

    void CreatMax(const StepID& key)
    {
        for(StepID i =0;i<key;i++){
            std::mutex m;
            _mutexes.emplace(std::piecewise_construct, std::forward_as_tuple(i),
                             std::forward_as_tuple());
        }
    }

private:
    std::unordered_map<StepID, std::mutex> _mutexes;
};


// typedef MJointData CJ;

class CombineJoint
{
public:
    CombineJoint();

    void MergeJoint(const StepID &i,const MJointData &j);

    void MergeCXJ(const StepID &i,const CXJ &j);

    void Start(std::string csv);

    void CreateEmptyJoint(int st);

    void ReadCSV(std::string csv);

    void MergeOne(const CSVRowJoint &cj);

    void SerialALL();

    std::map<StepID,CXJ> m_d;

    std::vector<CSVRowJoint> csvJJ;

    KeyMutexMap keyMutexMap;
};


#endif // COMBINEJOINT_H
